<template>
  <div class="box">
    <header class="header">
      <div class="left"><span @click="back" class="iconfont icon-zuo"></span></div>
      <div class="center">购物车</div>
      <div class="right"></div>
    </header>
    <div class="content">
      <div class="tologin" v-if="!login_state">
        <span class="tologin-tips">登录后将同步您的购物车商品</span>
        <a class="tologin-btn" href="#/login">登录</a>
      </div>
      <div class="hasLogin" v-if="login_state">
        <ul>
          <li  class="" v-for="(item,index) of cartlist" :key="item.cartid" @click.self="toDetail(item.productid)">
            <div class="checkbox">
              <input type="checkbox" v-model="item.flag" @change="selectItem(item, $event)">
              <span v-if="!item.flag"></span>
              <span v-else class="iconfont icon-gou"></span>
            </div>
            <div class="product-item">
                <div class="img">
                  <img :src="item.img" alt="">
                </div>
                <div class="info_box">
                  <p class="product_info">[{{item.typename}}]{{item.product_info}}</p>
                  <div class="changenum_box">
                    <span>数量</span>
                    <div class="btn_box">
                      <span v-if="item.num > 1" class="sub_btn" @click="reduce(item)">-</span>
                      <span v-else class="iconfont icon-lajitong add_del" @click="deleteItem(item.cartid,index)"></span>
                      <input type="text" disabled v-model="item.num">
                      <span class="add_btn" @click="add(item)">+</span>
                    </div>
                  </div>
                  <p class="product_price">￥{{item.price}}</p>
                </div>
            </div>
          </li>
        </ul>
        <div class="pay_btn" v-if="hasgoods">
          <van-submit-bar
            :price="totalPrice * 100"
            :button-text="'去结算(' + totalNum + ')'"
            @submit="onSubmit"
          >
            <van-checkbox v-model="allchecked" @click="selectAll">全选</van-checkbox>
          </van-submit-bar>
        </div>
      </div>
      <div class="notlogin" v-if="!hasgoods">
        <div class="emptycart">
          <img class="img" src="https://img02.hua.com/m/Shopping/m_shopping_empty_cart.png?v2" alt="" />
          <p class="text">购物车内暂时没有商品</p>
          <a class="home" href="/">去逛逛</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { mapState, mapMutations, mapGetters } from 'vuex'
import * as types from '@/store/mutation.types'
import { SubmitBar, Dialog, Toast, Checkbox } from 'vant'
import { getCartData, updateCartData, deleteCartData, addOrder } from '@/api'
Vue.use(SubmitBar)
Vue.use(Dialog)
Vue.use(Toast)
Vue.use(Checkbox)
export default {
  data () {
    return {
      login_status: false,
      allchecked: true,
      hasgoods: false
    }
  },
  methods: {
    ...mapMutations('users', [types.CHANGE_LOGIN_STATE]),
    back () {
      this.$router.go(-1)
    },
    toDetail (productid) {
      console.log(productid)
      this.$router.push({ path: '/detail/' + productid })
    },
    ...mapMutations('cart', [types.CHANGE_CART_LIST]),
    selectItem (item, event) {
      console.log(item)
      console.log(event.target.checked)
      // 后端实现接口，给后端传入 cartid 以及 event.target.checked，如果成功执行以下操作
      item.flag = event.target.checked
      if (event.target.checked) {
        this.allchecked = this.cartlist.every(item => {
          return item.flag
        })
      } else {
        this.allchecked = false
      }
    },
    selectAll (event) {
      this.allchecked = !this.allchecked
      // if (checked) {
      //   this.cartlist.map(item => {
      //     item.flag = true
      //   })
      // } else {
      //   this.cartlist.map(item => {
      //     item.flag = false
      //   })
      // }
      this.cartlist.map(item => {
        item.flag = this.allchecked
      })
    },
    add (item) {
      // item.num += 1
      updateCartData({ cartid: item.cartid, num: item.num + 1 }).then(res => { // 数据库更新完毕
        console.log(res.data)
        if (res.data.code === '200') {
          item.num += 1 // 修改页面
        }
      })
    },
    reduce (item) {
      // item.num -= 1
      updateCartData({
        cartid: item.cartid,
        num: item.num > 1 ? item.num - 1 : 1
      }).then(res => { // 数据库更新完毕
        console.log(res.data)
        if (res.data.code === '200') {
          // item.num -= 1 // 修改页面
          item.num > 1 ? item.num -= 1 : item.num = 1
        }
      })
    },
    deleteItem (cartid, index) {
      Dialog.confirm({
        title: '删除',
        message: '你确认要删除该商品吗？'
      }).then(() => {
        // on confirm
        deleteCartData({ cartid }).then(res => {
          if (res.data.code === '200') {
            // 修改状态
            this.cartlist.splice(index, 1)
            if (this.cartlist.length) {
              this.hasgoods = false
            }
          }
        })
      }).catch(() => {
        // on cancel
      })
    },
    onSubmit () {
      // 需要判定有没有选中商品，没有给予提示
      if (this.totalNum === 0) {
        Toast.fail('请先勾选你要购买的东西')
      } else {
        // Toast('确认订单')
        const arr = []
        this.cartlist.map(item => {
          if (item.flag) {
            arr.push(item)
          }
        })
        addOrder({
          userid: localStorage.getItem('userid'),
          // 选中商品即为 arr
          orderlist: JSON.stringify(arr)
        }).then(res => {
          console.log(res)
          // 返回一个订单id，跳转页面传递订单id
          this.$router.push('/order/' + res.data.orderid)
        })
      }
    }
  },
  computed: {
    ...mapState({
      cartlist: ({ cart }) => cart.cartlist,
      login_state: ({ users }) => users.login_state
    }),
    ...mapGetters('cart', ['totalNum']),
    totalPrice () {
      if (this.login_state) {
        return this.cartlist.reduce((sum, item) => {
          return item.flag ? sum + item.price * item.num : sum + 0
        }, 0)
      } else {
        return 0
      }
    }
  },
  mounted () {
    getCartData({
      userid: localStorage.getItem('userid')
    }).then(res => {
      console.log(res.data.data)
      this[types.CHANGE_CART_LIST]({
        payload: res.data.data
      })
      if (this.cartlist) {
        this.hasgoods = true
      }
      // console.log(this.$store.getters['cart/totalNum'])
    })
    console.log(this.hasgoods)
    console.log(this.login_state)
  }
}
</script>

<style scoped lang="scss">
.box {
  .header {
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    padding: {
      left: 20px;
      right: 20px;
    }
  }
  .content {
     background: #E9ECF0;
    .tologin {
      font-size: 14px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      background: #fff0ec;
      border: 1px solid rgba(255, 115, 76, 0.2);
    }
    .hasLogin {
      ul {
        li {
          background-color: #fff;
          border-top: 2px solid #E9ECF0;;
          display: flex;
          .checkbox {
            position: relative;
            display: flex;
            align-items: center;
            padding: 10px;
            input {
              width: 20px;
              height: 20px;
              opacity: 0;
              position: absolute;
              z-index: 1;
            };
            span {
              display: block;
              width: 20px;
              height: 20px;
              border: 1px solid #ff734c;
              border-radius: 50%;
              text-align: center;
              line-height: 20px;
              &.icon-gou {
                color: #ff734c;
                font-size: 20px;
              }
            }
          }
          .product-item {
            display: flex;
            align-items: center;
            .img {
              display: block;
              margin: 10px;
              width: 35%;
              img {
                width: 100%;
              }
            }
            .info_box {
              height: 100%;
              padding: {
                top: 20px;
                bottom: 20px;
              };
              .product_info {
                font-size: 14px;
              }
              .changenum_box {
                margin-top: 10px;
                display: flex;
                background-color: #fff;
                .btn_box {
                  margin-left: 15px;
                  border: 1px solid #E9ECF0;
                  background-color: #F7F9FA;
                  span {
                    display: inline-block;
                    width: 20px;
                    text-align: center;
                    &.icon-lajitong {
                      font-size: 12px;
                    }
                  }
                  input {
                    border: 0;
                    outline: 0;
                    width: 30px;
                    background-color: #F7F9FA;
                    border: {
                      left: 1px solid #E9ECF0;
                      right: 1px solid #E9ECF0;
                    };
                    text-align: center;
                  }
                }
              }
              .product_price {
                margin-top: 40px;
                font-size: 16px;
                color: #ff734c;
              }
            }
          }
        }
      }
      .pay_btn{

      }
    }
    .notlogin {
      background-color: #fff;
      padding: {
        top: 50px;
        bottom: 50px;
      };
      .emptycart {
        text-align: center;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        img {
          width: 120px;
        }
        .text {
          margin-top: 20px;
        }
        .home {
          display: block;
          text-underline: none;
          margin-top: 20px;
          width: 100px;
          height: 30px;
          line-height: 30px;
          background-color: #ff734c;
          color: #fff;
          font-size: 15px;
          border-radius: 15px;
        }
      }
    }
  }
}
</style>
